﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;

namespace Quickuse.Logging.FileLogger
{
    /// <summary>
    /// FileLoggerProvider
    /// </summary>
    internal sealed class FileLoggerProvider : LoggerProvider
    {
        private readonly ConcurrentDictionary<string, FileLogger> _loggers = new ConcurrentDictionary<string, FileLogger>();
        private IFileLoggerSettings _fileLoggerSettings;
        private IExternalScopeProvider scopeProvider;

        /// <summary>
        /// FileLoggerProvider
        /// </summary>
        /// <param name="fileLoggerSettings">fileLoggerSettings</param>
        /// <param name="fileLoggerProcessor">fileLoggerProcessor</param>
        /// <param name="filter">filter</param>
        public FileLoggerProvider(IFileLoggerSettings fileLoggerSettings, FileLoggerProcessor fileLoggerProcessor, Func<string, LogLevel, bool> filter = null)
            : base(fileLoggerProcessor.EnqueueMessage, filter)
        {
            if (fileLoggerSettings == null)
            {
                throw new ArgumentNullException(nameof(fileLoggerSettings));
            }

            _fileLoggerSettings = fileLoggerSettings;
            if (_fileLoggerSettings.ChangeToken != null)
            {
                _fileLoggerSettings.ChangeToken.RegisterChangeCallback(OnConfigurationReload, null);
            }
        }

        private void OnConfigurationReload(object state)
        {
            try
            {
                // The settings object needs to change here, because the old one is probably holding on
                // to an old change token.
                _fileLoggerSettings = _fileLoggerSettings.Reload();

                var scopeProvider = GetScopeProvider();
            }
            catch (Exception ex)
            {
                InternalLog.Error($"while loading configuration changes.{Environment.NewLine}{ex}");
            }
            finally
            {
                // The token will change each time it reloads, so we need to register again.
                if (_fileLoggerSettings?.ChangeToken != null)
                {
                    _fileLoggerSettings.ChangeToken.RegisterChangeCallback(OnConfigurationReload, null);
                }
            }
        }

        /// <summary>
        /// GetScopeProvider
        /// </summary>
        /// <returns></returns>
        private IExternalScopeProvider GetScopeProvider()
        {
            if (_fileLoggerSettings.IncludeScopes && scopeProvider == null)
            {
                scopeProvider = new LoggerExternalScopeProvider();
            }
            return _fileLoggerSettings.IncludeScopes ? scopeProvider : null;
        }

        /// <summary>
        /// CreateLogger
        /// </summary>
        /// <param name="categoryName">categoryName</param>
        /// <returns></returns>
        public override ILogger CreateLogger(string categoryName)
        {
            return _loggers.GetOrAdd(categoryName, (categoryName1) =>
            {
                return new FileLogger(categoryName1, _fileLoggerSettings, LogCallback, Filter, GetScopeProvider());
            });
        }

        /// <summary>
        /// 
        /// </summary>
        public override void Dispose()
        {
            //throw new NotImplementedException();
        }
    }
}
